<template>
  <div class="chat-room">
    <div class="message-list">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="{ self: message.to != $store.state.user.id }"
      >
        <div class="message-item" v-if="message.to == $store.state.user.id ">
          <!-- 别人发的消息主体 -->
          <div class="block">
            <el-avatar :size="35" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png">user</el-avatar>
          </div>
          <div class="message-content" v-if="message.type == 1">
            <span>{{ message.msg }}</span>
          </div>
          <div class="message-content" v-else>
            <img :src="message.msg" style="width: 20%">
          </div>

        </div>

        <div class="message-item" v-else>
          <!-- 自己发的消息主体 -->
          <div class="message-content" v-if="message.type == 1">
            <span>{{ message.msg }}</span>
          </div>
          <div class="message-content" style="text-align: right" v-else>
            <img :src="message.msg" style="width: 20%">
          </div>
          &nbsp;
          <div class="block"><el-avatar :size="35" :src="selfAvatar"></el-avatar></div>
        </div>
      </div>
    </div>
    <!-- 这里是输入框和发送按钮 -->
    <div class="message-send">
      <el-row :gutter="8">

        <el-col :span="16">
          <el-input v-model="message.msg" :disabled="message.type == 2" placeholder="请输入消息内容" clearable></el-input>
        </el-col>

        <el-col :span="5">
          <el-upload
            ref="upload"
            :action="uploadImgUrl"
            list-type="picture"
            :before-upload="handleBeforeUpload"
            :on-change="handleChange"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleRemove"
            :headers="headers">
            <el-button round type="success"><i class="el-icon-upload el-icon--left"></i>选择文件</el-button>
          </el-upload>
        </el-col>

        <el-col :span="3">
          <el-button @click="send" round  type="primary">发送</el-button>
        </el-col>

      </el-row>
    </div>
  </div>
</template>

<script>
import {getToken} from "@/utils/auth";

export default {
  props: ["ws","to"],
  data() {
    return {
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/uploadOSS", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      selfAvatar: "", // 自己头像
      messages: [
        { msg: '我也很高兴来到这里',to:"1",  type: 1},
        { msg: '你好，欢迎来到聊天室',to:"2", type: 1},
        { msg: '你好',to:"1", type: 1},
      ],

      message: {
        from: this.$store.state.user.id,
        to: this.to,
        msg: "",
        type: 1, // 1[正常消息],2[图片]
      },
      imageUrl:"", // 图片附件url
    };
  },
  methods: {
    // 文件状态改变时的钩子
    handleChange() {
      this.message.type = 2;
    },
    // 删除文件
    handleRemove(file, fileList) {
      this.imageUrl = "";
      this.message.type = 1;
      this.$notify({
        title: '图片已取消',
        message: '已取消发送图片',
        type: 'info'
      });
    },
    // 上传前方法
    handleBeforeUpload(file) {
      this.$modal.loading("正在上传文件，请稍候...");
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.message.type = 1;
      this.$modal.closeLoading();
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      console.log(res);
      if (res.code === 200) {
        // 将图片地址添加到字段
        this.imageUrl = res.url;
        this.$notify({
          title: '图片已选择',
          message: '请点击发送按钮发送图片',
          type: 'success'
        });
      }
      // 取消加载框
      this.$modal.closeLoading();
    },


    send() {
      if (this.ws) {

        // 深拷贝避免数据响应式变换
        const message = JSON.parse(JSON.stringify(this.message));

        // 如果是图片 进行url上传
        if(this.message.type == 2){
          message.msg = this.imageUrl;
        }

        if(!message.msg){
          this.$message.error("不允许发送空消息！");
          return false;
        }
        this.ws.send(JSON.stringify(message));

        // 加入展示数组
        this.$message.success("消息发送成功！",message.from,message.to);

        this.messages.unshift(message);

        // 成功之后字段清空 并清空图片url
        this.message.type = 1;
        this.message.msg = "";
        this.$refs.upload.clearFiles();


      } else {
        this.$message.error("未连接到服务器");
      }
    }
  },
  mounted(){
    // 加载头像
    this.selfAvatar = this.$store.state.user.avatar;

    // 接收到服务端消息
    this.ws.onmessage = (event) => {
      // 深拷贝避免数据响应式变换
      let message = JSON.parse(JSON.stringify(this.message));

      let data = JSON.parse(event.data);
      message.to = data.to;
      message.from = data.from;
      message.msg = data.msg;
      message.type = data.type;

      this.messages.unshift(message);
    };

    // websocket关闭事件
    this.ws.addEventListener('close', () => {
      console.log('WebSocket closed');
    });

    // websocket错误事件
    this.ws.addEventListener('error', (err) => {
      console.error('WebSocket error:', err);
    });
  }
}
</script>
<style scoped>
.message-list {
  display: flex;
  flex-direction: column-reverse;
}

.self {
  display: flex;
  justify-content: flex-end;
  font-family: "楷体", Courier, monospace;
}

.message-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.message-content {
  margin-left: 10px;
}
</style>
